// 组织树对象    当前处理树的node
var permissionTree,dealTreeNode1;
var isAddSysPer=false,isUpdateSysPer=false;
// 当前操作节点
var curNode;
$(function(){
	getDpType();
	// 初始化树
	$("#tree").height($(window).height()- 100);
	permissionTree = $.fn.zTree.init($("#tree"), setting, zNodes);
	var rootNode = permissionTree.getNodes()[0];
	
	var FirstNode=$("#FirstNode").val();
	curNode = permissionTree.getNodeByParam("id",FirstNode);
	permissionTree.selectNode(curNode,false,false);
	
	permissionTree.expandNode(rootNode);
	dealTreeNode = rootNode;
	isUpdateSysOrg = false;
	isAddSysOrg = false;
	
	//permissionTree.expandAll(true);
	$('#permissionObj').bootstrapValidator(validator);
	
});

// 基础设置
var setting = {
		
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			$('#permissionShow').show();
			$('#menuInfoWell').hide();
			if(treeNode.permId!=null&&treeNode.permId!=null){
				treeNode.id=treeNode.permId;
			}
			showPermission(treeNode.id);
			curNode = treeNode;
		}
	}

};
//获取数据权限定义的种类，赋给下拉框。
var DpType
function getDpType(){
	$('#DpType').empty();
	$.ajax({
		url:"../dataPermissionController/getType",
		dataType:"json",
		type:"post",
		success:function(data){
			DpType=data;
			$('#DpType').append('<option value=""></option> ');
			for (var i = 0; i < data.length; i++) {
				$('#DpType').append("<option value='"+data[i].ID+"'>"+data[i].LABEL+"</option>")
			}
			
		}
	});
}
//刷新站点树
function refreshTree(){
	$.post('refreshTree.action',{},function(data){
		permissionTree.destroy('tree');
		permissionTree = $.fn.zTree.init($("#tree"), setting, data);
		var rootNode = permissionTree.getNodes()[0];
		permissionTree.expandNode(rootNode);
		dealTreeNode = rootNode;
		showPermission(rootNode.id);
		isUpdateSysOrg = false;
		isAddSysOrg = false;
	});
}

//展开所有
function expandAll(){
	permissionTree.expandAll(true);
}

//关闭所有
function collapseAll(){
	permissionTree.expandAll(false);
}

/*///展开所有
function eAll(){
	$('#permissionTreeTable').treeTable('expandAll');
	return true;
}

//关闭所有
function cAll(){
	$('#permissionTreeTable').treeTable('collapseAll');
	return false;
}*/


/**
 * 查找所有父节点
 * @param data
 * @returns {Array}
 */
function findRootNodes(data){
	var rootNodes = new Array();
	for(var i=0;i<data.length;i++){
		var hasParent = false;
		for(var j=0;j<data.length;j++){
			if(data[i].parentId == data[j].permId){
				hasParent = true;
				break;
			}
		}
		if(!hasParent){
			rootNodes.push(data[i]);
		}
	}
	return rootNodes;
}

/**
 * 排序节点
 * @param curId
 * @param newArray
 * @param oldArray
 */
function sortOrder(curId,newArray,oldArray){
	for(var i=0;i<oldArray.length;i++){
		if(oldArray[i].parentId == curId){
			newArray.push(oldArray[i]);
			sortOrder(oldArray[i].permId,newArray,oldArray);
		}
	}
}

//初始化treetable
function inittreeTable(){
	$('#permissionTreeTable').empty();
	
}

//展示列表
function showlist(){
	inittreeTable();
	$.post('selectPerAll.action',{},function(data){                       
		var rootNodes = findRootNodes(data);
		var newArray = new Array();
		for(var i=0;i<rootNodes.length;i++){
			newArray.push(rootNodes[i]);
			sortOrder(rootNodes[i].permId,newArray,data);
		}
		for(var i=0;i<newArray.length;i++){
			var tmpStr = newArray[i].uri;
			if(newArray[i].uri.length > 20){
				tmpStr = newArray[i].uri.substring(0,20)+'&#8230;';
			}
			$('#permissionTreeTable').append('<tr id="'+newArray[i].permId+'" pId="'+newArray[i].parentId+'"><td>'+newArray[i].permCode+'</td><td>'+newArray[i].permName+'</td><td><span title="'+newArray[i].uri+'">'+tmpStr+'</span></td>'+'<td id="perm'+newArray[i].permId+'" >'+newArray[i].permType+'</td><td>'+newArray[i].permIcon+'</td><td>'+newArray[i].permCheck+'</td><td>'+newArray[i].permSort+'</td></tr>'); 
			var permType=newArray[i].permType;
			if("1"==permType){
				$("#perm"+newArray[i].permId).html("菜单");
			}
			if("2"==permType){
				$("#perm"+newArray[i].permId).html("标签");
			}
			if("3"==permType){
				$("#perm"+newArray[i].permId).html("请求");
			}
		}
		
	    $('#permissionTreeTable').treeTable({ 
	    	expandLevel : 1, column:0, expandable: true
	    	}).show();
	});
	$('#PermissionHeader').hide();
	$('#PermissionContainer').hide();
	$('#PermissionContainer2').show();
	$('#saveBtn').show();
	$('#updateBtn').show();
}

// 初始化页面
function initFrame(){
	$('#permissionObj input').val('');
	$('#permissionObj [name=type]').val('1');
	$('#permissionObj [name=grade]').val('-1');
	resetValidator();
	
}

function resetValidator(){
	if($('#permissionObj').data('bootstrapValidator')){
		$('#permissionObj').data('bootstrapValidator').resetForm(false);
	}
}

// 展示添加权限页面
function addPermission(){
	if(!curNode){
		alertModel('请选择父节点');
		return;
	}
	initFrame();
	//$('#permissionObj').bootstrapValidator(validator);
	$('#permissionShow').hide();
	$('#menuInfoWell').show();
	$('#dealPermission').show();
	$('#updatePermissionbtn').hide();
	$('#parentIdVal').val(curNode.id);
	$('#parentName').html(curNode.name);
	$('#dealPermission').html('保存');	
	
/*$('#dealPermission').unbind('click').bind('click',function(){savePermission();});
*/	
	
}

// 保存权限信息
function savePermission(){
	$.post('saveSysPermission.action',$('#permissionObj').serialize(),function(data){
		var permission = {'id':data.permId,'name':data.permName,'parentId':curNode.id};
		permission.name=data.permName;
		var curNode1 = permissionTree.addNodes(curNode, permission);
		curNode=curNode1[0];
		var aa=curNode;
		showData(data);
		$('#permissionShow').show();
		$('#menuInfoWell').hide();
		isClick=false;
	});
}

// 删除权限信息
/*function delPermission(){
	if(!curNode){
		alertModel('请选择需删除的节点');
		return;
	}
	if(10==curNode.id){
		alertModel('根权限禁止删除');
		return;
	}
	if(confirmModel('确定删除'+curNode.name)){
		 var treeObj = $.fn.zTree.getZTreeObj("tree");
		 var treeNode = treeObj.getSelectedNodes();
		 var childNodes = treeObj.transformToArray(treeNode);
	     var nodes = new Array();
	     for(var i = 0; i < childNodes.length; i++) {
	    	 nodes.push(childNodes[i].id);
	     }
	     var ids= nodes.join(",");
		$.post('delByPrimaryId.action',{'ids':ids},function(){
			
				var ptId = curNode.parentTId;
				permissionTree.removeNode(curNode);
				
				curNode = permissionTree.getNodeByTId(ptId);	
				showPermission(curNode.id);
			
		});
	}
}*/



function delPermission(){
	if(!curNode){
		alertModel('请选择需删除的节点');
		return;
	}
	if(1==curNode.id){
		alertModel('根权限禁止删除');
		return;
	}
	confirmModel('确定删除'+curNode.name+'及其子节点么？',delPermission1,"")
	
}
function delPermission1(){
var treeObj = $.fn.zTree.getZTreeObj("tree");
var treeNode = treeObj.getSelectedNodes();
var childNodes = treeObj.transformToArray(treeNode);
var nodes = new Array();
for(var i = 0; i < childNodes.length; i++) {
	 nodes.push(childNodes[i].id);
}
var ids= nodes.join(",");
$.post('delByPrimaryId.action',{'ids':ids},function(){
	    $('#_frm_confirm_modal').modal('hide');
		var ptId = curNode.parentTId;
		permissionTree.removeNode(curNode);
		curNode = permissionTree.getNodeByTId(ptId);
		if(curNode)
			showPermission(curNode.id);
		searchTable.ajax.reload();
	
});
}
// 展示权限信息
function showPermission(id){
	$.post('searchByPrimaryKey.action',{'permId':id},function(data){
			showData(data);
	});
}

function showUpdate(){
	if(!curNode){
		alertModel('请选择需修改节点');
		return;
	}
	
	initFrame();
	var aa = curNode.id;
	//$('#permissionObj').bootstrapValidator(validator);
	
	$.post('searchByPrimaryKey.action',{'permId':curNode.id},function(data){
		
		for(col in data){
			
			$('#permissionObj [name='+col+']').val(data[col]);
				
		}
	});
	$('#permissionShow').hide();
	$('#menuInfoWell').show();
	$('#dealPermission').hide();
	$('#updatePermissionbtn').show();
	$('#parentIdVal').val(curNode.id);
	var ptId = curNode.parentTId;
	var pNode = permissionTree.getNodeByTId(ptId);
	if(!pNode==0){
	$('#parentName').html(pNode.name);
	}else
		{
		$('#parentName').html('');
		}
	$('#updatePermissionbtn').html('修改');
	isClick1=false;
	//$('#dealPermission').unbind('click').bind('click',function(){updatePermission();});
}
var searchTable;
//查看用户
function showStaff(){
	if(!curNode){
		alertModel('请选择需查询的节点');
		return;
	}
	/*if(!searchTable){*/
		// 后面构建btn 代码
		var btnModel = '    \
			{{#each func}}\
		    <button type="button" class="user-button btn-sm" onclick="{{this.fn}}">{{this.name}}</button>\
		    {{/each}}';
		
		var template = Handlebars.compile(btnModel);
		var aa=curNode;
		// datatables 
//		searchTable='';
		$("#searchTable").DataTable().destroy();
		searchTable = $("#searchTable").DataTable({
			"ordering": false,// 排序
			"serverSide": true,// 开启服务器模式
			"scrollX": true,// 横向滚动
			ajax:{
	            "type": "POST",
	            "url":'searchPermissionStaff.action',//请求路径
	            "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
	            "dataType":'json',
	            "data":{"permId":curNode.id},
//	            "data":function(d){// 查询参数
//	            	d.permId = curNode.id;
//	            	alert(d.permId);
//	            	return d;
//	            }
			},    
			columns: [// 对应列
			    
			    {"data": "id"},
			    {"data": null},
	            {"data": "code",render : $.fn.dataTable.render.ellipsis(22, true)},
	            {"data": "name",render : $.fn.dataTable.render.ellipsis(22, true)},
	            {"data": "account",render : $.fn.dataTable.render.ellipsis(22, true)},
	            {"data": "orgName",render : $.fn.dataTable.render.ellipsis(22, true)},
	            {"data": "sex"},
	            {"data": "phone"},
	            {"data": "email"},
	            {"data": "mobilPhone"},
	            {"data": "status"}
	            
	        ],
	        "columnDefs": [
				{// 所有列默认值
					"targets": "_all",
					"defaultContent": ''
				},
				{// 隐藏第一列
					"targets": 0,
					"visible": false 
				},
				{
					targets: 6,
		            render: function (a, b, c, d) {
		                if('M' == c.sex){
		                	return '男';
		                }else{
		                	return '女';
		                }
		            }
				},
				{
					targets: 10,
					render: function (a, b, c, d){
						if('1' == c.status)return '有效';else return '无效';
					}
				},
				{// 最后一列添加按钮
		            targets: 1,
		            render: function (a, b, c, d) {
		                context =
		                {
		                    func: [
		                        {"name": "详细信息", "fn": "showEditPage(\'" + c.id + "\')", "type": "primary"}
		                    ]
		                };
		                var html = template(context);
		                return html;
		            }
		        }]
			,"dom": 'rt<"bottom"ip><"clear">' //生成样式
		});	
	/*}else{
	searchTable.ajax.reload();
	}*/
	$('#PermissionHeader').hide();
	$('#PermissionContainer').show();
	$('#PermissionContainer2').hide();
	//$('#saveBtn').show();
	//$('#updateBtn').show();
	
	
}

//详细信息展示
function showEditPage(id){
	
//	$.post('searchSysStaffById.action',{'id':id},function(data){
//		$('#statusStaffObjdiv').removeClass('HdClass');
//		$("#hiddenId").val(id);
//		$('#PermissionHeader').hide();
//		$('#PermissionContainer').hide();
//		$('#PermissionContainer2').hide();
//		$('#staffContainer').show();
//		
//		// 展示人员信息
//		var sysStaff = data.staffObj;
//		$("#codeStaffObj").val(sysStaff["staffCode"]);
//		$("#nameStaffObj").val(sysStaff["staffName"]);
//		$("#personTypeStaffObj").val(sysStaff["personType"]);
//		$("#empCodeStaffObj").val(sysStaff["empCode"]);
//		$("#statusStaffObj option[value='"+sysStaff["staffStatus"]+"']").attr("selected",true);
//		$("#sexStaffObj option[value='"+sysStaff["sex"]+"']").attr("selected",true);
//		$("#originalHireDateStaffObj").val(sysStaff["hireDate"]);
//		$("#postcodeStaffObj").val(sysStaff["postcode"]);
//		$("#mailAddrStaffObj").val(sysStaff["mailAddr"]);
//		$("#phoneStaffObj").val(sysStaff["phone"]);
//		$("#emailStaffObj").val(sysStaff["email"]);
//		$("#mobilPhoneStaffObj").val(sysStaff["mobilPhone"]);
//		$("#accountStaffObj").val(sysStaff["loginName"]);
//		$("#passwdStaffObj").val(sysStaff["passwd"]);
//		
//	});
var url = prc + "/sysStaffController/goStaffInfo?staffId="+id;
$("#jump_url").attr("src", url);
$('#infoModal').modal({
	'show' : true
});
}



//初始化页面信息
function initFrame1(){
	$('#PermissionHeader').show();
	$('#staffContainer').hide();
	$('#PermissionContainer').hide();
	$('#PermissionContainer2').hide();
	$('#saveBtn').hide();
	/*if(searchTable!=''){
		searchTable.destroy();
	}*/
	
}


//返回
function backSearch(){
	initFrame1();
}
/*//详细信息进入后返回
function backSearch1(){
	initFrame2();
}
function initFrame2(){
	//$('#PermissionHeader').show();
	$('#staffContainer').hide();
	$('#PermissionContainer2').hide();
	$('#PermissionContainer').show();
}*/

// 更新至数据库
function updatePermission(){
	$.post('updatePermission.action',$('#permissionObj').serialize(),function(data){
		permissionTree.editName(curNode);
		permissionTree.cancelEditName(data.name);
		
		showPermission(curNode.id);
		$('#permissionShow').show();
		$('#menuInfoWell').hide();
		curNode.name=data.permName;
		permissionTree.updateNode(curNode);
		alertModel("修改成功!");
		});
	
}


function showData(data){
	for(col in data){
		if('permType' == col){
			if('1' == data[col]){
				$('#sysPermissionType').html('菜单');
			}else if('2' == data[col]){
				$('#sysPermissionType').html('标签');
			}else if('3' == data[col]){
				$('#sysPermissionType').html('请求');
			}
		}/*else if('controlLevel' == col){
			if('-1' == data[col]){
				$('#sysPermissionGrade').html('无限制');
			}else if('100' == data[col]){
				$('#sysPermissionGrade').html('集团公司');
			}else if('200' == data[col]){
				$('#sysPermissionGrade').html('省公司');
			}else if('300' == data[col]){
				$('#sysPermissionGrade').html('地市公司');
			}else if('400' == data[col]){
				$('#sysPermissionGrade').html('区县公司');
			}
		}*/else if('grade' == col){}/*else{
			$('#sysPermission'+upperHead(col)).html(data[col]);
		}*/
		else if('permCode' == col){
			$('#sysPermissionCode').html(data[col]);
		}
		else if('permName' == col){
			$('#sysPermissionName').html(data[col]);
		}
		else if('uri' == col){
			$('#sysPermissionUri').html(data[col]);
		}
		else if('permType' == col){
			$('#sysPermissionType').html(data[col]);
		}
		else if('permIcon' == col){
			$('#sysPermissionIcon').html(data[col]);
		}
		else if('permCheck' == col){
			$('#sysPermissionCheck').html(data[col]);
		}
		else if('permSort' == col){
			$('#sysPermissionSort').html(data[col]);
		}else if('dataPermissionType' == col){
			var type="";
			for (var i = 0; i < DpType.length; i++) {
				if (DpType[i].ID==data[col]) {
					type=DpType[i].LABEL;
				}
			}
			$('#sysPermissionDP').html(type);
		}
		
	}
}
var isClick=false;
function ifclick(){
	isClick=true;
}
var isClick1=false;
function ifclick1(){
	isClick1=true;
}
var validator = {
		message: '请核对此字段的输入',
		feedbackIcons: {
	        valid: 'glyphicon glyphicon-ok',
	        invalid: 'glyphicon glyphicon-remove',
	        validating: 'glyphicon glyphicon-refresh'
	    },
	    submitHandler: function(validator, form, submitButton) {
	    	if(isClick){
	    		savePermission();
	    	}
	    	if(isClick1){
	    		updatePermission();
	    	}
	    	//$('#dealPermission').bind('click',function(){savePermission();});
	    	//$('#updatePermissionbtn').bind('click',function(){updatePermission();});

        },
	    fields: {
	    	permCode: {
	            validators: {
	                notEmpty: {
	                    message: '请输入权限编码'
	                }
	            },
	            stringLength: {   
	                max: 20,  
	                message: '权限编码不大于20个字符'  
	                } 
	        },
	        permName: {
	            validators: {
	                notEmpty: {
	                    message: '请输入权限名称'
	                }
	            },
	            stringLength: {   
	                max: 20,  
	                message: '权限名称不大于20个字符'  
	                } 
	        },
	        uri: {
	            validators: {
	            	 stringLength: {  
			                max: 50,  
			                message: '权限地址不大于50个字符'  
			                } 
	            },
	               
	            },
	            permIcon: {
		            validators: {
		            	 stringLength: {  
				                max: 100,  
				                message: '菜单图标不大于100个字符'  
				                } 
		            },
		               
		            },
		        permCheck: {
			            validators: {
			            	 stringLength: {  
					                max: 60,  
					                message: '校验字符不大于60个字符'  
					                } 
			            },
			               
			            },
	            permSort: {
		            validators: {
		            	stringLength: {  
				            max: 10,  
				            message: '展示顺序不大于10个字符'  
				                  }, 
		            	numeric: {
							message: "只能输入纯数字"

						},
		            },
		        }
	        
	    }
	};
   